package utils;

import java.sql.*;


public class JDBCutil {
    private static Connection con;
    private static PreparedStatement ps;
    private static ResultSet rs;
    public static Connection getCon() {
        return con;
    }
//    连接数据库
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mysql";
            String user = "root";
            String password = "root";
            con= DriverManager.getConnection(url,user,password);
        } catch (Exception e) {
            throw new RuntimeException(e + "连接数据库失败");
        }
    }

//增删改方法
    public static int excuteUpdate(String sql,Object[] obj){
        int result=-1;
        try {
            ps=con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i+1,obj[i]);
            }
            result=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
//查询全部
    public static ResultSet excuteQuery(String sql){
        try {
            ps=con.prepareStatement(sql);
            rs=ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    return rs;
    }
//查询单条数据
public static ResultSet excuteQuery(String sql,String sth){
    try {
        ps=con.prepareStatement(sql);
        ps.setObject(1,sth);
        rs=ps.executeQuery();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return rs;
}
//
//关闭,节约资源
public static void close(){
    try {
        if (con!=null){con.close();}
        if (ps!=null){ps.close();}
        if (rs!=null){rs.close();}
    } catch (SQLException e) {
        e.printStackTrace();
    }


}

}